import { useNavigate } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { useMessage } from './useAppMessage'
import useTableSearch from './useTableSearch'
import useTableSortable from './useTableSortable'
import useUpdateMutation from './useUpdateMutation'

export const useTableList = ({
  params = {},
  listQueryHook,
  updateMutationHook,
  deleteMutationHook,
  sortable = true,
  simpleSort = false,
  pagination = true,
}) => {
  const message = useMessage()
  const navigate = useNavigate()

  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [tableData, setTableData] = useState([])

  const { cursort, sorts, onTableChange } = useTableSortable({ simple: simpleSort })
  const { search, onClear, getColumnSearchProps } = useTableSearch()

  const queryConfig = { ...params, ...search }
  if (sortable && sorts.length) {
    queryConfig.sort = JSON.stringify(sorts)
  }
  if (pagination) {
    queryConfig.page = page
    queryConfig.per_page = pageSize
  }
  const { isPending, isSuccess, data, refetch } = listQueryHook(queryConfig)

  useEffect(() => {
    console.log('%c Line:37 🍿 data', 'color:#33a5ff', data)
    if (pagination && data) {
      setPage(+data.current_page)
      setTotal(data.total)
      setTableData(data.data)
    } else {
      setTableData(data)
    }
  }, [isSuccess, data])

  let onChangePage
  if (pagination) {
    onChangePage = (page, pageSize) => {
      setPage(page)
      setPageSize(pageSize)
    }
  }

  let onUpdate, debounceUpdate
  if (updateMutationHook) {
    const updateMethods = useUpdateMutation(updateMutationHook, {
      onSuccess() {
        refetch()
        navigate({ to: '.' })
      },
    })
    onUpdate = updateMethods.onUpdate
    debounceUpdate = updateMethods.debounceUpdate
  }

  let onBatchDelete
  if (deleteMutationHook) {
    const { mutate: deleted } = deleteMutationHook()
    onBatchDelete = (ids) => {
      if (!deleteMutationHook) return
      if (ids.length === 0) return message.error('请选择要删除的记录')
      console.log('%c 删除的ID =>', 'color:#42b983', ids)
      deleted(ids)

      // 清除条件，刷新列表
      // onClear({})
    }
  }

  return {
    isPending,
    cursort,
    data: tableData,
    page,
    pageSize,
    total,
    getColumnSearchProps,
    refetch,
    onUpdate,
    debounceUpdate,
    onChangeTable: onTableChange,
    onChangePage,
    onBatchDelete,
  }
}
